package com.qf.microuser.point.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qf.common.core.entity.PointInfo;
import com.qf.common.core.entity.PointRetry;
import com.qf.microuser.point.mapper.PointRetryMapper;
import com.qf.microuser.point.service.PointInfoService;
import com.qf.microuser.point.service.PointRetryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * 2024/12/31
 */
@Service
public class PointRetryServiceImpl implements PointRetryService {
    @Resource
    private PointRetryMapper pointRetryMapper;

    @Resource
    private PointInfoService pointInfoService;

    @Override
    public void addPointRetry(PointRetry pointRetry) {
        pointRetryMapper.insert(pointRetry);
    }

    @Override
    public void pointRetryTask() {
        // 获取所有的补偿数据
        List<PointRetry> pointRetries = pointRetryMapper.selectList(null);
        // 循环遍历每个记录,将数据添加到积分记录表,超过一定次数则不再补偿
        for (PointRetry retry : pointRetries) {
            // 如果已经超过3次,则不再补偿
            if (retry.getRetryNum().equals(3)) {
                break;
            }
            PointInfo info = new PointInfo();
            info.setUid(retry.getUid());
            info.setPoint(retry.getPoint());
            info.setPointType(retry.getPointType());
            //可以用多线程进行优化
            try {
                pointInfoService.addPointInfo(info);
                // 如果成功,删除记录
                pointRetryMapper.deleteById(retry.getId());

            } catch (Exception e) {
                e.printStackTrace();
                // 如果失败,修改补偿次数
                retry.setRetryNum(retry.getRetryNum() + 1);
                pointRetryMapper.update(null,
                        new LambdaUpdateWrapper<PointRetry>()
                                .set(PointRetry::getRetryNum, retry.getRetryNum())
                                .eq(PointRetry::getId, retry.getId()));
            }
        }
    }
}
